#include "comm.hpp"

int main()
{
    // 1.创建公共的key值
    key_t key = ftok(PATH_NAME, PROJ_ID);
    log("create key done", Debug) << " server key: " << std::hex << (int)key << endl;

    // 2.创建共享内存
    int shmid = shmget(key, SHM_SIZE, IPC_CREAT | IPC_EXCL | 0666);
    if (shmid == -1)
    {
        perror("shmget");
        exit(1);
    }
    log("create shm done", Debug) << " server key: " << shmid << endl;
    // sleep(10);

    // 3.将指定的共享内存，挂接到自己的进程地址空间
    char *shmaddr = (char *)shmat(shmid, nullptr, 0);
    log("attach shm done", Debug) << " server key: " << shmid << endl;
    // sleep(10);

    //使用
    while(1)
    {
        cout << shmaddr << endl;
        sleep(1);
    }
    
    // 4.将共享内存与进程地址空间去关联
    int n = shmdt(shmaddr);
    assert(n != -1);
    (void)n;
    log("detach shm done", Debug) << " server key: " << shmid << endl;

    //删除共享内存,IPC_RMID即便是有进程与当前共享内存挂接,依旧删除共享内存
    int ret = shmctl(shmid, IPC_RMID, nullptr);
    assert(ret != -1);
    (void)ret;

    return 0;
}